package com.itheima.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URI;
import java.net.http.HttpRequest;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.rmi.ServerException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class TextToSpeechUtils {

    //保存文件
    public static void textToSpeech(String text) throws IOException {
        String groupId = "1698299595062679";
        String apiKey = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJOYW1lIjoi5Lit6IGadGVzdCIsIlN1YmplY3RJRCI6IjE2OTg0MDQ2MTQ0NDEzMDIiLCJQaG9uZSI6IiIsIkdyb3VwSUQiOiIxNjk4Mjk5NTk1MDYyNjc5IiwiUGFnZU5hbWUiOiIiLCJNYWlsIjoiIiwiQ3JlYXRlVGltZSI6IjIwMjMtMTAtMzAgMDk6MDc6NTkiLCJpc3MiOiJtaW5pbWF4In0.u_hddxsFQ1oLSB5Pf0Vm1Z_4y1et-rwGUidNT6NbCMg2Uk4-UbNPGQjNUaPKWmRzGnqisf_x1lKrBD1eHTxoIiQDXWbMfoZ3IXs3mpwQeV2KFtecJwvrjgSLwNUdmkEu3JpYqjtFIWZjucQnmw6ThWStjp925u6TJVLrE1e_kSmf02nbfXpgk5OOitAvhekbPjt4lT3fUN6z_gZ7gJllUdvAIGPZKLH5xl7udA2RSEWz9P98lDMagfqOwDJtLWPk9wbaIAESRupPZVTMUbYNcvtcadLT3eXi3we8JDKJ4Zz7NGSlcLRyIfMUmSWPWmeQkx4Ask0I4vV5_cK2v3d2wQ";
        String apiUrl = "https://api.minimax.chat/v1/text_to_speech?GroupId=" + groupId;

        // 创建请求体的 Map
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("voice_id", "male-qn-qingse");
        requestBody.put("text", text);
        requestBody.put("model", "speech-01");
        requestBody.put("speed", 1.0);
        requestBody.put("vol", 1.0);
        requestBody.put("pitch", 0);

        // 创建 HttpClient 对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

            // 创建 POST 请求
            HttpPost httpPost = new HttpPost(apiUrl);
            // 设置请求头部信息
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", "Bearer " + apiKey);

            // 将请求体转换为 JSON 字符串
            String json = JSON.toJSONString(requestBody);

            // 设置请求体
            StringEntity requestEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(requestEntity);

            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                if (response.getStatusLine().getStatusCode() != 200 || response.getEntity().getContentType().getValue().contains("json")) {
                    System.out.println(response.getEntity().getContent());
                    log.info("调用失败: " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
                    throw new ServerException("调用失败: " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
                }

                try (InputStream inputStream = response.getEntity().getContent();
                     OutputStream outputStream = new FileOutputStream("D:\\output.wav")){
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                }

                System.out.println("文件下载成功");
                System.out.println("trace_id: " + response.getFirstHeader("Trace-Id").getValue());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }


    //返回byte[]
      public byte[] textToSpeechTest(String text) {
          String groupId = "1698299595062679";
          String apiKey = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJOYW1lIjoi5Lit6IGadGVzdCIsIlN1YmplY3RJRCI6IjE2OTg0MDQ2MTQ0NDEzMDIiLCJQaG9uZSI6IiIsIkdyb3VwSUQiOiIxNjk4Mjk5NTk1MDYyNjc5IiwiUGFnZU5hbWUiOiIiLCJNYWlsIjoiIiwiQ3JlYXRlVGltZSI6IjIwMjMtMTAtMzAgMDk6MDc6NTkiLCJpc3MiOiJtaW5pbWF4In0.u_hddxsFQ1oLSB5Pf0Vm1Z_4y1et-rwGUidNT6NbCMg2Uk4-UbNPGQjNUaPKWmRzGnqisf_x1lKrBD1eHTxoIiQDXWbMfoZ3IXs3mpwQeV2KFtecJwvrjgSLwNUdmkEu3JpYqjtFIWZjucQnmw6ThWStjp925u6TJVLrE1e_kSmf02nbfXpgk5OOitAvhekbPjt4lT3fUN6z_gZ7gJllUdvAIGPZKLH5xl7udA2RSEWz9P98lDMagfqOwDJtLWPk9wbaIAESRupPZVTMUbYNcvtcadLT3eXi3we8JDKJ4Zz7NGSlcLRyIfMUmSWPWmeQkx4Ask0I4vV5_cK2v3d2wQ";
          String apiUrl = "https://api.minimax.chat/v1/text_to_speech?GroupId=" + groupId;
          HttpHeaders headers = new HttpHeaders();
          headers.setContentType(MediaType.APPLICATION_JSON);
          headers.set("Content-Type", "application/json");
          headers.set("Authorization", apiKey);

          Map<String, Object> requestBody = new HashMap<>();
          //requestBody.put("GroupId", 1698299595062679);
          //requestBody.put("timber_weights", request.getTimberWeights());
          requestBody.put("model", "speech-01");
          requestBody.put("text", text);


          requestBody.put("voice_id", "male-qn-qingse");
          requestBody.put("speed", 1.0);
          requestBody.put("vol", 1.0);
          requestBody.put("pitch", 0);


          HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(requestBody, headers);
          RestTemplate restTemplate = new RestTemplate();

          // 发送请求
          byte[] bytes = restTemplate.postForObject(apiUrl, httpEntity, byte[].class);
          assert bytes != null;
          System.out.println(Arrays.toString(bytes));
          return bytes;
      }

}



